import LoadRemotePlist from '../Download/LoadRemotePlist';
/**
 * 用途         :读取本地数据,读取服务器数据
 * 开发者       :郑品延
 * 修改时间     :2019/8/6
 */
export default class LoadUtil{
    //这里是同步里面的promise函数,提供自由化搭配
    public static loadResAltasFunc(atlasPath, imgName){
        return new Promise<cc.SpriteFrame>((resolve,reject)=>{
            atlasPath = 'Atlas/' + atlasPath;
            cc.loader.loadRes(atlasPath, cc.SpriteAtlas, function (err, atlas) {
                if (err) {
                    Log(err.message);
                    reject(null);
                    return;
                }
                else{
                    var frame = atlas.getSpriteFrame(imgName);
                    Log('获取到图集图片');
                    resolve(frame);
                }
            });
        })
    }
    public static loadResImgFunc(addres){
        return new Promise<cc.SpriteFrame>((resolve,reject)=>{
            cc.loader.loadRes(addres, cc.SpriteFrame, function (err, spFrame) {
                if (err) {
                    Log(err.message);
                    reject(null);
                    return;
                }
                else{
                    Log('获取到背景图片')
                    resolve(spFrame);
                }
            });
        })
    }
    public static loadNetImgFunc(addres){
        return new Promise<cc.SpriteFrame>((resolve,reject)=>{
            cc.loader.load({ url: addres, type: 'png' }, function (err, spFrame) {
                if(err){
                    Log('加载网络图片错误>:',err.message)
                    reject(null);
                    return;
                }
                else{
                    let spr = new cc.SpriteFrame(spFrame);
                    resolve(spr);
                }
            });
        })
    }
    public static loadPrefabFunc(addres){
        addres = 'Prefab/' + addres;
        return new Promise<cc.Node>((resolve,reject)=>{
            cc.loader.loadRes(addres, function (err, prefab) {
                if(err){
                    Log('加载预制体错误>:',err)
                    return;
                }
                var prefabNode = cc.instantiate(prefab);
                resolve(prefabNode);
            });
        })
    }
    //加载本地龙骨动画,url 填Spine文件夹下的大文件夹就行
    public static loadDragonResSync(node, url,back?) {
        return new Promise<cc.SpriteFrame>((resolve,reject)=>{
            url = 'Spine/' + url
            var animationDisplay = node.getComponent(dragonBones.ArmatureDisplay);
            cc.loader.loadResDir(url, function(err, assets){
                if(err || assets.length <= 0)  {
                    Log('加载龙骨动画失败 ',err);
                    reject(null);
                    return;
                }
                assets.forEach(asset => {
                    if(asset instanceof dragonBones.DragonBonesAsset){
                        animationDisplay.dragonAsset = asset;
                    }
                    if(asset instanceof dragonBones.DragonBonesAtlasAsset){
                        animationDisplay.dragonAtlasAsset  = asset;
                    }
                });
                animationDisplay.armatureName = 'Sprite';
                resolve();
                // animationDisplay.addEventListener(dragonBones.EventObject.COMPLETE, back);
            })
            // cc.loader.load({ url: addres, type: 'png' }, function (err, spFrame) {
            //     if(err){
            //         Log('加载网络图片错误>:',err.message)
            //         reject(null);
            //         return;
            //     }
            //     else{
            //         let spr = new cc.SpriteFrame(spFrame);
            //         resolve(spr);
            //     }
            // });
        })
        url = 'Spine/' + url
        var animationDisplay = node.getComponent(dragonBones.ArmatureDisplay);
        cc.loader.loadResDir(url, function(err, assets){
            if(err || assets.length <= 0)  {
                Log('加载龙骨动画失败 ',err)
                return;
            }
            assets.forEach(asset => {
                if(asset instanceof dragonBones.DragonBonesAsset){
                    animationDisplay.dragonAsset = asset;
                }
                if(asset instanceof dragonBones.DragonBonesAtlasAsset){
                    animationDisplay.dragonAtlasAsset  = asset;
                }
            });
            animationDisplay.armatureName = 'Armature';
            // animationDisplay.addEventListener(dragonBones.EventObject.COMPLETE, back);
        })
    }
    //------------------------------------------这里是同步写法,需要用到时候这样写,下面的是写法,这个上面的是能直接调用的--------------------

    public static async loadResAtlasSync(container, atlasPath, imgName,callback?){
        let promiseFunc = (atlasPath, imgName)=>{
            return new Promise((resolve,reject)=>{
                atlasPath = 'Atlas/' + atlasPath;
                cc.loader.loadRes(atlasPath, cc.SpriteAtlas, function (err, atlas) {
                    if (err) {
                        Log(err);
                        reject(null);
                        return;
                    }
                    else{
                        var frame = atlas.getSpriteFrame(imgName);
                        resolve(frame);
                    }
                });
            })
        }
        container.spriteFrame = await promiseFunc(atlasPath, imgName);
        callback && callback();
    }

    public static async LoadNetImgSync(container, addres,callback?){
        let promiseFunc = (addres)=>{
            return new Promise((resolve,reject)=>{
                cc.loader.load({ url: addres, type: 'png' }, function (err, spFrame) {
                    if(err){
                        Log('加载网络图片错误>:',err.message);
                        reject(null);
                        return;
                    }
                    else{
                        Log('同步加载图片完成!')
                        let spr = new cc.SpriteFrame(spFrame);
                        resolve(spr);
                    }
                });
            })
        }
        container.spriteFrame = await promiseFunc(addres);
        callback && callback();
    }


    //-------------------------------------------------同步结束---------------------------------------------

    public static SaveLocal(key,value){
        cc.sys.localStorage.setItem(key+'', value+'');
    }
    public static ReadLocal(key,defaultValue){
        var value = cc.sys.localStorage.getItem(key+'');
        if (!value) {
            return defaultValue;
        }
        return value;
    }
    public static RemoveLocal(key){
        cc.sys.localStorage.removeItem(key);
    }
    //--------------------------------------------------加载资源的一堆函数
    public static loadRes (url, type, callback?) {           //加载本地数据,也是下面的基础
        if (!url) {
            return;
        }
        cc.loader.loadRes(url, type, function (err, res) {
            if (err) {
                Log('---------loadRes err: ' + err.message);
                return;
            }
            if (callback) {
                callback(res);
            }
        });
    }
    //加载本地图集中的图片
    public static LoadResAtlas(container, atlasPath, imgName,callback?) {
        if (!container || !atlasPath || !imgName || imgName == '') {
            return;
        }
        let cmpPath = 'Atlas/' + atlasPath;
        cc.loader.loadRes(cmpPath, cc.SpriteAtlas, function (err, atlas) {
            if(err){
                Log('本地图集没有此文件,尝试去下载文件中读取')
                LoadUtil.loadNetAtlas(container, atlasPath, imgName,callback)
                return;
            }
            var frame = atlas.getSpriteFrame(imgName);
            container.spriteFrame = frame;
            if (callback) {
                callback();
            }
        });
    }
    //加载下载到本地的图集
    public static loadNetAtlas(container, atlasPath, imgName,callback){
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            return;
        }
        let url = tt.env.USER_DATA_PATH + '/' + atlasPath + '.plist';
        LoadRemotePlist.loadPlist(url,(err,atlas)=>{
            if (err) {
                cc.error('错误信息',err);
                return;
            }
            container.spriteFrame = atlas.getSpriteFrame(imgName);
            if (callback){
                callback();
            }
        })
    }
    //加载网络图片
    public static LoadNetImg (container, addres,callback?) {
        if (container == null || container == 'null') {
            return;
        }
        if (addres == null || addres == 'null') {
            return;
        }
        if (addres === "") {
            return;
        }
        // if (addres.indexOf('http') == 0) {
            cc.loader.load({ url: addres, type: 'png' }, function (err, spFrame) {
                if(err){
                    Log('加载网络图片错误>:',err.message)
                    return;
                }
                container.spriteFrame = new cc.SpriteFrame(spFrame);
                if (callback) {
                    callback();
                }
            });
        // }
        // else{
        //     Log('不合格图片')
        // }
    }
    //加载本地未合图的图片
    public static LoadResImg(container, addres, callback?) {
        if (!container || !addres) {
            return;
        }
        cc.loader.loadRes(addres, cc.SpriteFrame, function (err, spFrame) {
            if (err) {
                // cc.error(err.message);
                Log('加载本地图片出错 = ', err.message)
                return;
            }
            container.spriteFrame = spFrame;
            if (callback) {
                callback();
            }
        });
    }
    public static readJsonData(str,callback?) {
        LoadUtil.loadRes('/Json/' + str,cc.JsonAsset ,(res) => {
            if (!res) {
                return;
            }
            if (callback)
            {
                callback(res.json);
            }
        });
    }
    /**
     * 保存JSON文件 需要在拥有jsb环境下执行
     * @param str 本地resouces/Json文件夹下的json文件名
     * @param obj 要保存的对象,会在函数内转成字符串
     */
    public static saveJsonData(str,obj){
        try {
            var pathurl = cc.url.raw("resources/Json") + "/"+str+".json";
            jsb.fileUtils.writeStringToFile(JSON.stringify(obj), pathurl);
        } catch (error) {
            Log('不支持JSB环境,不能写入本地文件,请删除LoadUtil.saveJsonData的调用')
        }

    }
    public static readNetJson(url,callback?){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    if (response) {
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    } else {
                        Log("返回数据不存在")
                        callback(false);
                    }
                } else {
                    Log("请求netjson失败")
                    callback(false);
                }
            }
        };
        xhr.open("GET", url);
        xhr.send();
    }
    //加载本地龙骨动画,url 填Spine文件夹下的大文件夹就行
    public static loadDragonRes(node, url,back?) {
        if (!url || !node) {
            back(null);
            return;
        }
        url = 'Spine/' + url
        var animationDisplay = node.getComponent(dragonBones.ArmatureDisplay);
        cc.loader.loadResDir(url, function(err, assets){
            if(err || assets.length <= 0)  {
                Log('加载龙骨动画失败 ',err)
                return;
            }
            assets.forEach(asset => {
                if(asset instanceof dragonBones.DragonBonesAsset){
                    animationDisplay.dragonAsset = asset;
                }
                if(asset instanceof dragonBones.DragonBonesAtlasAsset){
                    animationDisplay.dragonAtlasAsset  = asset;
                }
            });
            animationDisplay.armatureName = 'Armature';
            // animationDisplay.addEventListener(dragonBones.EventObject.COMPLETE, back);
        })
    }
    //addPrefab 加载预制体
    public static addPrefab(url, parent, callback = null) {
        Log('预制的父节点',parent);
        let parentNode = parent
        cc.loader.loadRes(url,  (err, prefab) => {
            if(err){
                Log('加载预制体错误>:',err)
                return;
            }
            var prefabNode = cc.instantiate(prefab);
            prefabNode.parent = parentNode;
            if (callback) {
                callback(prefabNode);
            }
        });
    }
}
window['ReadLocal'] = LoadUtil.ReadLocal;
window['SaveLocal'] = LoadUtil.SaveLocal;
window['LoadNetImg'] = LoadUtil.LoadNetImg;
window['LoadResImg'] = LoadUtil.LoadResImg;
window['LoadResAtlas'] = LoadUtil.LoadResAtlas;
window['RemoveLocal'] = LoadUtil.RemoveLocal;
window['LoadNetImgSync'] = LoadUtil.LoadNetImgSync;